import json
import random


def show_menu():
    """首页展示"""
    print()
    print('==========欢迎来到考试管理系统==========')
    print('1: 开始考试  2: 添加问题 3:退出')


def add_question():
    """添加问题"""
    question = input('请输入问题: ')
    A = input('请输入答案A: ')
    B = input('请输入答案B: ')
    C = input('请输入答案C: ')
    D = input('请输入答案D: ')
    right = input('请输入正确选项: ')
    while True:
        if right not in ('A', 'B', 'C', 'D'):
            right = input('输入错误,请重新输入: ')
        else:
            break

    dict1 = {'question': question, 'A': A, 'B': B, 'C': C, 'D': D, 'right': right}

    with open('../99 文件目录/考题.txt', 'w', encoding="utf-8") as f:
        f.write(json.dumps(dict1))


def exam():
    """开始考试"""
    score = 0
    with open('../99 文件目录/考题.txt', 'r', encoding="utf-8") as f:
        list = f.readlines()
        contents = random.sample(list, 5)
        for a, b in enumerate(contents):
            dict1 = json.loads(b)
            print(str(a + 1) + ': ' + dict1.get('question') + '?')
            print('A: ' + dict1.get('A'), end='\t')
            print('B: ' + dict1.get('B'), end='\t')
            print('C: ' + dict1.get('C'), end='\t')
            print('D: ' + dict1.get('D'))
            right = input('请输入正确选项: ')
            while True:
                if right not in ('A', 'B', 'C', 'D'):
                    right = input('输入错误,请重新输入: ')
                else:
                    if right == dict1.get('right'):
                        score += 20
                        print('回答正确')
                    else:
                        print('回答错误')
                    break
    print('考试结束,总成绩: %d' % score)


while True:
    show_menu()
    num = int(input('请输入: '))
    if num == 1:
        exam()
    elif num == 2:
        add_question()
    elif num == 3:
        print('已退出')
        break
    else:
        print('输入错误')
